<template>
	<view :class="item.mediaType=='video'?'video-view':'upload-view'">
		<view :class="item.mediaType=='video'?'upload-view-video':'upload-view-image'">
			<!-- <button type="primary" :loading="loading" :disabled="disabled" @click="upload">选择照片</button> -->


			<image
				:style="type =='inputPanel'?'background-color:#f0f0f0;width:144rpx;height:144rpx':'background-color:#f0f0f0'"
				v-if="item.mediaType=='image'|| item.mediaType=='img'" :src="item.url" mode="scaleToFill"
				class="uploadImage" />
			<!-- 视频长传的时候显示本地视频 -->
			<!-- <video id="myVideo" style="width: 672rpx;height: 522rpx;" v-if="item.mediaType=='video'&&!item.url"  :src="item.filePath" enable-danmu controls  direction="90"></video> -->
			<!-- 上传成功显示服务器端视频 -->
			<image mode="aspectFill" style="background-color:#f0f0f0;width: 672rpx;height: 522rpx;"
				@click="videoPlay(item.url)" v-if="item.mediaType=='video'" id="myVideo" :src="poster">
			</image>
			<!-- 视频播放按钮 -->
			<!-- <view @click="videoPlay(item.url)" v-if="item.mediaType=='video'&&item.url" class="play">
					  <image style="width:120rpx;height:120rpx" src="../../static/x.png"></image>
					</view> -->
			<!-- 删除按钮 -->
			<image v-if="item.url" class="delImg" src="../../static/x.png" mode="scaleToFill" @click="delImg" />
		</view>
		<view class="upload-view-progress" v-if="showProgress || !item.url">
			<progress activeColor="#ea5404" :percent="percent" stroke-width="10"></progress>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	const util = require('../../utils/util.js');
	const dialog = require('../../utils/dialog.js');

	// #ifdef APP-PLUS

	const PluginModule = uni.requireNativePlugin("PluginModule");
	import {
		requestAndroidPermission,
		gotoAppPermissionSetting
	} from "@/utils/permission.js"
	// #endif
	var _self;
	export default {
		props: {
			item: {
				type: Object,
				default () {
					return {
						type: 0,
						mediaType: 'add',
						url: '',
						path: '',
						uuid: util.createUidKey()
					}
				}
			},
			sourceFileList: {
				type: Array,
				default () {
					return []
				}
			},
			type: {
				type: String,
				default () {
					return ''
				}
			},
			// poster: String

		},
		data() {
			return {
				percent: 0,
				loading: false,
				disabled: false,
				showProgress: false,
				snaptshotUrl: '',
				poster:''
			}
		},
		computed: {

		},
		onLoad() {

		},
		methods: {
			// 评论上传图片
			upload(index, from) {
				console.log(index, from)
				var that = this
				if (this.item.url) {
					uni.showToast({
						icon: 'none',
						title: '请删除后重新上传'
					})
					return
				}
				if (index == 3) {
					// #ifdef APP-PLUS
					this.uploadAlbum(index);
					// #endif
					// #ifdef MP-WEIXIN
					this.uploadAlbumWx(index);
					// #endif
				} else if (index == 2) {
					// #ifdef H5
					this.uploadH5();
					// #endif
					// #ifdef APP-PLUS
					this.uploadAlbum(index);
					// #endif
					//#ifdef MP-WEIXIN
					this.uploadAlbumWx();
					// #endif
				} else if (index == 1) {
					// #ifdef H5 ||APP-PLUS
					this.recordNativeMedia();
					// #endif

					//#ifdef MP-WEIXIN
					console.log("调用微信拍摄功能")
					if (from == "发动态") {
						console.log('*************来源微信端发动态')
						uni.chooseMedia({
							count: 1,
							mediaType: ['image', 'video'],
							sourceType: ['camera'],
							maxDuration: 30,
							camera: 'back',
							success(res) {
								var type = res.type
								if (that.sourceFileList.length > 1) {
									if (that.sourceFileList[1].mediaType != type) {
										uni.showToast({
											icon: 'none',
											title: '视频或者图片只能选择一种上传'
										})
										return
									}
								}
								console.log(res)
								if (res.tempFiles[0].duration > 30) {
									uni.showToast({
										icon: 'none',
										title: '上传视频不能超过30S'
									})
									return
								}
								// type = res.tempFiles[0].fileType
								that.uploadFilePre(res.tempFiles[0].tempFilePath, type, res.tempFiles[0]
									.thumbTempFilePath);
							}
						})


					} else {
						console.log('*************来源其他')
						uni.chooseImage({
							count: 1,
							sourceType: ['camera'],
							success: (res) => {
								var type = 'image'
								console.log(that.sourceFileList)
								if (that.sourceFileList.length > 1) {
									if (that.sourceFileList[1].mediaType != type) {
										uni.showToast({
											icon: 'none',
											title: '视频或者图片只能选择一种上传'
										})
										return
									}
								}
								that.uploadFilePre(res.tempFiles[0].path, type);
							},
							fail: (err) => {
								console.log(err, 'err')
							},
						});
					}
					// #endif
				}
			},
			uploadAlbumWx() {
				//todo 图片最多限制，视频上传后不能上传图片限制
				var that = this;
				if (this.sourceFileList[0].mediaType == "video") {
					uni.showToast({
						icon: 'none',
						title: '视频或者图片只能选择一种上传'
					})
					return
				}
				uni.chooseMedia({
					count: 1,
					sourceType: ['album'],
					success: (res) => {
						console.log(res)
						// that.tempImg = res.tempFiles[0].thumbTempFilePath
						// this.uploadFile(res.tempFilePaths[0])
						var type = 'image'
						console.log(that.sourceFileList)
						if (that.sourceFileList.length > 1) {
							if (that.sourceFileList[0].mediaType != type) {
								uni.showToast({
									icon: 'none',
									title: '视频或者图片只能选择一种上传'
								})
								return
							}
						}
						if (res.tempFiles[0].duration > 30) {
							uni.showToast({
								icon: 'none',
								title: '上传视频不能超过30S'
							})
							return
						}
						type = res.tempFiles[0].fileType
						that.uploadFilePre(res.tempFiles[0].tempFilePath, type, res.tempFiles[0]
							.thumbTempFilePath)
						// that.uploadFile(res.tempFilePaths[0], type);

					},
					fail: (err) => {
						console.log(err, 'err')
					},
				});
			},
			uploadAlbum(index) {
				//todo 图片最多限制，视频上传后不能上传图片限制
				var that = this;
				if (this.sourceFileList[0].mediaType == "video") {
					uni.showToast({
						icon: 'none',
						title: '视频或者图片只能选择一种上传'
					})
					return
				}
				if (index == 3) {
					uni.chooseImage({
						count: 1,
						sourceType: ['album'],
						success: (res) => {
							var type = 'image'

							if (that.sourceFileList.length > 1) {
								if (that.sourceFileList[0].mediaType != type) {
									uni.showToast({
										icon: 'none',
										title: '视频或者图片只能选择一种上传'
									})
									return
								}
							}
							that.uploadFilePre(res.tempFilePaths[0], type);

						},
						fail: (err) => {
							console.log(err, 'err')
						},
					});
				} else {
					uni.chooseVideo({
						count: 1,
						sourceType: ['album'],
						success: (res) => {
							var type = 'video'
							console.log(res)
							if (that.sourceFileList.length > 1) {
								if (that.sourceFileList[0].mediaType != type) {
									uni.showToast({
										icon: 'none',
										title: '视频或者图片只能选择一种上传'
									})
									return
								}
							}
							if (res.duration > 30) {
								uni.showToast({
									icon: 'none',
									title: '上传视频不能超过30S'
								})
								return
							}

							that.uploadFilePre(res.tempFilePath, 'video')

						},
						fail: (err) => {
							console.log(err, 'err')
						},
					});
				}

			},
			uploadFilePre(fileUrl, mediaType, poster) {
				var _self = this;
			
				var uploadUrl = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_ALIYUN_OSS_UPLOAD
				_self.item.filePath = fileUrl;
				_self.item.mediaType = mediaType;
				var poster = poster || fileUrl
				console.log(fileUrl, mediaType)
				_self.$emit('uploading', _self.item, poster)
				console.log("上传啦")
				// // #ifdef MP-WEIXIN
				// uni.showLoading({
				//     title: mediaType == 'video' ? "视频上传中" : "图片上传中",
				//     mask: true
				// })
				// // #endif
				try {
					var uploadTask = uni.uploadFile({
						url: uploadUrl, //仅为示例，非真实的接口地址
						filePath: fileUrl,
						name: 'file',
						success: (uploadFileRes) => {
							console.log(JSON.stringify(uploadFileRes))
							//小程序原生请求要先处理statusCode
							if (uploadFileRes.statusCode == 200) {
								var uploadFileData = JSON.parse(uploadFileRes.data);
								console.log("上传成功" + uploadFileRes.data);
								uni.hideLoading()
								if (uploadFileData.code == 200) {
									
									var datapath = uploadFileData.data
									_self.item.url = datapath;
									_self.showProgress = false;
									_self.$emit('success', _self.item)
									// resolve( _self.item); 
									// _self.$emit('transCover', _self.poster)
								} else {
									uni.showToast({
										title: "上传失败" + uploadFileData.message,
										duration: 3000,
										icon: 'none'
									})
									_self.$emit('error', _self.item)
								}
							} else {
								uni.hideLoading()
								uni.showToast({
									title: "上传失败，请重试",
									duration: 3000,
									icon: 'none'
								})
								uploadTask.abort()
								_self.$emit('error', _self.item)
							}
						},
						fail(e) {
							console.log(e)
						}
					});
					uploadTask.onProgressUpdate(function(res) {
						_self.percent = res.progress;
				
						if (!res.progress || res.progress < 100) {
							_self.showProgress = true;
						}
						if (res.progress >= 100) {
							_self.showProgress = false;
							// uni.showLoading({
							// 	title: "文件数据处理中",
							// 	mask: true
							// })
							// uni.showToast({
							// 	title: "文件数据处理中",
							// 	duration: 3000,
							// 	icon: 'none'
							// })
				
						}
					});
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
			},
			videoPlay(src) {

				if (this.showProgress == true) {
					uni.showToast({
						icon: 'none',
						title: '视频未上传成功'
					})
					return
				} else if (!src) {
					// uni.showToast({
					// 	icon: 'none',
					// 	title: '视频数据处理中,请稍后'
					// })
					return
				} else {
					uni.navigateTo({
						url: '/module_my/pages/videoDetail/videoDetail?src=' + src
					})
				}
			},
			play() {

			},
			
			
			uploadingCallBack(fileUrl,resolve,reject){
				var _self=this
				var uploadUrl = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_ALIYUN_OSS_UPLOAD
				try {
					var uploadTask = uni.uploadFile({
						url: uploadUrl, //仅为示例，非真实的接口地址
						filePath: fileUrl,
						name: 'file',
						success: (uploadFileRes) => {
							console.log(JSON.stringify(uploadFileRes))
							//小程序原生请求要先处理statusCode
							if (uploadFileRes.statusCode == 200) {
								var uploadFileData = JSON.parse(uploadFileRes.data);
								console.log("上传成功" + uploadFileRes.data);
								uni.hideLoading()
								if (uploadFileData.code == 200) {
									
									var datapath = uploadFileData.data
									_self.item.url = datapath;
									_self.showProgress = false;
									//debugger
									// _self.$emit('success', _self.item)
									resolve( _self.item); 
									_self.$emit('transCover', _self.poster)
								} else {
									uni.showToast({
										title: "上传失败" + uploadFileData.message,
										duration: 3000,
										icon: 'none'
									})
									_self.$emit('error', _self.item)
								}
							} else {
								uni.hideLoading()
								uni.showToast({
									title: "上传失败，请重试",
									duration: 3000,
									icon: 'none'
								})
								uploadTask.abort()
								_self.$emit('error', _self.item)
							}
						},
						fail(e) {
							console.log(e)
						}
					});
					uploadTask.onProgressUpdate(function(res) {
						_self.percent = res.progress;
				
						if (!res.progress || res.progress < 100) {
							_self.showProgress = true;
						}
						if (res.progress >= 100) {
							_self.showProgress = false;
							// uni.showLoading({
							// 	title: "文件数据处理中",
							// 	mask: true
							// })
							// uni.showToast({
							// 	title: "文件数据处理中",
							// 	duration: 3000,
							// 	icon: 'none'
							// })
				
						}
					});
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
			},
			uploadFile(fileUrl, mediaType, poster) {
				console.log('小程序传视频的poster是个image' + poster)
				var _self = this;
				//debugger
				return new Promise((resolve, reject) => {
					// _self.$emit('uploading', _self.item, poster)
					
					
					_self.item.filePath = fileUrl;
					_self.item.mediaType = mediaType;
					// var poster = poster || fileUrl
					// _self.$emit('uploading', mediaType, poster,{uploadUrl,fileUrl,resolve,reject})
					if(mediaType=='video'){
						_self.uploadCover(mediaType,poster).then(
							res=>{
								//debugger
								_self.uploadingCallBack(fileUrl,resolve,reject)
							}
						)
					}else{
						//debugger
						_self.uploadingCallBack(fileUrl,resolve,reject)
					}
					
					console.log(fileUrl, mediaType)
					console.log("上传啦")
					
				})	
			},

			uploadCover(item, fileUrl) {//视频封面
				var _self = this
				// return new Promise((resolve, reject) => {
				console.log(item, fileUrl)
				// uni.showToast({
				// 	icon: 'none',
				// 	title: '进入uploadCover里了'+fileUrl
				// })
				//debugger
				return new Promise((resolve, reject)=>{
					// if (item == 'video') {
						// _self.fileList.splice(_self.fileList.findIndex(x => x.uuid === item.uuid), 1, item)
						// #ifdef APP-PLUS
						//debugger
						PluginModule.snapshotVideo({
							"path": fileUrl,
							"time": '2'
						}, response => {
							if(response.data=='获取截图失败。'){//截图获取失败
								var a=''
								resolve(a)
							}else{
								// uni.showToast({
								// 	icon: 'none',
								// 	title: '进入response里了'+response.data
								// })
								_self.uploadFileFM('file://' + response.data, 'image', true).then(res=>{
									resolve(res)
								})
							}
						})
						// #endif
						
						//#ifdef MP-WEIXIN
						//debugger
						_self.uploadFileFM(fileUrl, 'image', true).then(
							res=>{
								resolve(res)
							}
						)
						//#endif
						// return
					// 
				})
			},
			uploadFileFM(fileUrl, mediaType, isPoster) {
				return new Promise((resolve, reject) => {
					// uni.showToast({
					// 	icon: 'none',
					// 	title: fileUrl
					// })
					console.log("uploadFilefileUrl：" + fileUrl);
					// var fileUrl2 = plus.io.convertLocalFileSystemURL(fileUrl)
					// fileUrl = plus.io.convertAbsoluteFileSystem(fileUrl)
					// console.log("uploadFile fileUrl2："+fileUrl2);
					var _self = this;
					var uploadUrl = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_ALIYUN_OSS_UPLOAD
				
					var uploadTask = uni.uploadFile({
						url: uploadUrl, //仅为示例，非真实的接口地址
						filePath: fileUrl,
						name: 'file',
						success: (uploadFileRes) => {
							console.log(JSON.stringify(uploadFileRes))
							if (uploadFileRes.statusCode == 200) {
								var uploadFileData = JSON.parse(uploadFileRes.data);
								if (uploadFileData.code == 200) {
									//debugger
									var datapath = uploadFileData.data
									_self.poster = datapath
									resolve(datapath)
								}
							} else {
								uploadTask.abort()
							}
				
						},
						fail(e) {
							uni.showToast({
								icon: 'none',
								title: '视频封面上传失败'+fileUrl,
								duration: 10000,
							})
						}
					});
				})
			},

			
			delImg() {
				this.$emit('delete', this.item)

			}
		},
	}
</script>

<style scoped>
	.play {
		/*  width: 100%;
	  height: 100%; */
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		z-index: 1;
	}

	.play image {
		display: block;
		/* transform: translate(-50%,-50%);
		position: absolute;
		left: 50%;
		top: 50%; */
	}

	.upload-view {
		position: relative;
	}

	.video-view {
		position: relative;
	}

	.upload-view-progress {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 10px;
		z-index: 10;
	}

	.upload-view-video {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 672rpx;
		height: 522rpx;
		border-radius: 12rpx;
	}

	.upload-view-image {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		border-radius: 12rpx;
	}

	.uploadImage {
		width: 216rpx;
		height: 216rpx;
		border-radius: 12rpx;
	}

	.delImg {
		position: absolute;
		right: 0;
		top: 0;
		width: 40rpx;
		height: 40rpx;
		z-index: 2;
	}
</style>
